<?php

namespace App\Console\Commands;

use App\Models\AutoMoneyTransaction;
use App\Models\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CheckExpiredMembershipAutoTransactionsCommand extends Command
{
    /**
     * 命令名称
     *
     * @var string
     */
    protected $signature = 'money:check-expired-membership-auto-transactions';

    /**
     * 命令描述
     *
     * @var string
     */
    protected $description = '检查会员到期用户的定时记账数量，如果超过非会员限制，则保留最新的几个，其余自动禁用';

    /**
     * 执行命令
     */
    public function handle()
    {
        $this->info('开始检查会员到期用户的定时记账...');
        $now = Carbon::now();
        $this->info('当前时间: ' . $now->toDateTimeString());

        // 获取今天会员到期的用户
        $expiredMembershipUsers = User::where('membership_expires_at', '<', $now)
            ->where('membership_expires_at', '>=', $now->copy()->subDay())
            ->get();

        $this->info('找到 ' . $expiredMembershipUsers->count() . ' 个今天会员到期的用户');

        $maxAllowed = config('predefine.non_member_limits.max_record_by_cron', 1);
        $disabledCount = 0;

        foreach ($expiredMembershipUsers as $user) {
            // 获取用户的所有启用状态的定时记账
            $autoTransactions = AutoMoneyTransaction::where('user_id', $user->id)
                ->where('status', AutoMoneyTransaction::STATUS_ENABLED)
                ->orderBy('created_at', 'desc')
                ->get();

            $this->info("用户 ID={$user->id}, 名称={$user->name} 有 {$autoTransactions->count()} 个启用状态的定时记账");

            // 如果定时记账数量超过非会员限制，则保留最新的几个，其余自动禁用
            if ($autoTransactions->count() > $maxAllowed) {
                $toDisable = $autoTransactions->slice($maxAllowed);
                $this->info("需要禁用 {$toDisable->count()} 个定时记账");

                foreach ($toDisable as $transaction) {
                    try {
                        $transaction->status = AutoMoneyTransaction::STATUS_DISABLED;
                        $transaction->save();
                        $disabledCount++;
                        $this->info("已禁用定时记账: ID={$transaction->id}, 标题={$transaction->title}");
                    } catch (\Exception $e) {
                        $this->error("禁用定时记账失败: ID={$transaction->id}, 标题={$transaction->title}, 错误: {$e->getMessage()}");
                        Log::error("禁用定时记账失败", [
                            'transaction_id' => $transaction->id,
                            'error' => $e->getMessage(),
                            'trace' => $e->getTraceAsString()
                        ]);
                    }
                }
            }
        }

        $this->info("检查完成，共禁用 {$disabledCount} 个定时记账");
        return 0;
    }
}